var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "menuId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url:"nourl"
        }
    }
};
var ztree;


$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'course/course/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true },
			{ label: '课程名称', name: 'title', index: 'title', width: 100 },
            { label: '所需积分', name: 'integral', index: 'integral', width: 80 },
            { label: '课程介绍', name: 'introduce', index: 'introduce', width: 80 },
            { label: '课程须知', name: 'courseMustKnow', index: 'courseMustKnow', width: 80 },
			{ label: '类别', name: 'type', index: 'type', width: 60 },
			// { label: '级别', name: 'level', index: 'level', width: 60 },
			/*{ label: '创建时间', name: 'createTime', index: 'create_time', width: 80 },
			{ label: '订阅次数', name: 'subscribeTotal', index: 'subscribe_total', width: 80 },*/
			// { label: '方向', name: 'directionId', index: 'direction_id', width: 60 },
			// { label: '课程分类', name: 'classificationId', index: 'classification_id', width: 60 },
            { label: '负责人Id', name: 'teacherId', index: 'teacher_id', width: 60 },
            { label: '负责人姓名', name: 'teacherName', index: 'teacher_id', width: 60 },
			{ label: '封面图片路径', name: 'coverPath', index: 'cover_path', width: 80,
                formatter: function (data) {
                    return `<img src="${data}" style="height: 40px;width: 40px"></img>`;

                } },
            { label: '是否上线', name: 'isOnline', index: 'cover_path', width: 80,
                formatter: function (data,row) {
            	var html;
            	if(data==0){
            		html=` <button class="btn btn-primary" onclick="online(${row.rowId})"></i>&nbsp;未上线</button>`
				}else {
                    html=` <button class="btn btn-success"onclick="upline(${row.rowId})"></i>&nbsp;已上线</button>`

                }
                    return html;

                } }
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
    vm.getClassificationList();
    vm.getTeacherList();
    vm.getDirectionList();
    vm.getMenu();

    new AjaxUpload('#upload', {
        action: baseURL + "course/teacher/upload",
        name: 'file',
        autoSubmit:true,
        responseType:"json",
        onSubmit:function(file, extension){
            if (!(extension && /^(jpg|jpeg|png|gif)$/.test(extension.toLowerCase()))){
                alert('只支持jpg、png、gif格式的图片！');
                return false;
            }
        },
        onComplete : function(file, r){
            if(r.code == 0){
                $("#pic").attr('src',r.returnUrl);
                vm.course.coverPath=r.returnUrl
            }else{
                alert(r.msg);
            }
        }
    });


});

function online(id) {
    onlineWindow(id,1,"确认要上线么？")
}
function upline(id){
    onlineWindow(id,0,"确认要下架么？")
}

function onlineWindow(id,isOnline,msg){
    var data={
        id:id,
        isOnline:isOnline
    }
  confirm(msg, function(){
        $.ajax({
            type: "POST",
            url: baseURL + "course/course/online",
            contentType: "application/json",
            data: JSON.stringify(data),
            success: function(r){
                vm.reload()
                console.log(r)
                alert("操作成功")
            }
        });
    });
}


var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
        search:null,
        isOnline:null,
		title: null,
		course: {},
        classList:[],
		typeList:[
			{"name":"基础"},
			{"name":"案例"},
			{"name":"框架"},
			{"name":"工具"},
			{"name":"设计模式"}
		],
        levelList:[
            {"name":"入门"},
            {"name":"初级"},
            {"name":"中级"},
            {"name":"高级"},
            {"name":"专业"}
        ],
        classificaitonList:[],
        directionList:[],
        teacherList:[],
        menu:{
            parentName:null,
            parentId:0,
            type:1,
            orderNum:0
        }
	},
	methods: {
        getMenu: function(menuId){
            //加载菜单树
            $.get(baseURL + "course/classification/getClassificationTree", function(r){
                ztree = $.fn.zTree.init($("#menuTree"), setting, r.menuList);
               // var node = ztree.getNodeByParam("menuId", vm.menu.parentId);
                ztree.selectNode(node);
                //
                // vm.menu.parentName = node.name;
                console.log(baseURL)
            })
        },
        menuTree: function(){
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择菜单",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#menuLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    vm.course.classificationId = node[0].menuId;
                    vm.course.name = node[0].name;

                    layer.close(index);
                }
            });
        },
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.course = {classificationId:null,name:null};
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(id)
		},
        getDirectionList(){

            $.ajax({
                type: "POST",
                url: baseURL + "course/direction/list",
                contentType: "application/json",

                success: function(r){
                    console.log(r)
                    vm.directionList= r.page.list;
                }
            });

        },
        getTeacherList:function(){
		    $.ajax({
                type: "POST",
                url: baseURL + "course/teacher/getUserList",
                contentType: "application/json",
                success: function(r){
                    console.log(r)
                    vm.teacherList = r.page.list;
                }
            });
        },
        getClassificationList:function(){
            data={id:-2}
            $.ajax({
                type: "POST",
                url: baseURL + "course/classification/getClassification",
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function(r){
                    console.log(r)
                    vm.classificaitonList = r.page;
                }
            });
        },
		saveOrUpdate: function (event) {
			var url = vm.course.id == null ? "course/course/save" : "course/course/update";
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.course),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},

		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "course/course/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$.get(baseURL + "course/course/info/"+id, function(r){
                vm.course = r.course;
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData:{'search': vm.search,
                    'isOnline': vm.isOnline,
                    },
                page:page
            }).trigger("reloadGrid");
		}
	}
});